const { Op } = require('sequelize')

const Business = require('../model/business.model')

class operationBusiness {
	async find({ business_name, address }) {
		const res = await Business.findOne({
			where: {
				[Op.and]: {
					[Op.or]: {
						business_name,
						address
					},
					status: {
						[Op.or]: ['待审核', '营业中'],
					}
				}

			}
		})
		return res ? res.dataValues : null
	}
	async addBusiness({ business_name, address, phone, director, password }) {
		const data = await Business.create({
			business_name,
			address,
			director,
			phone,
			password
		})
		return data.dataValues
	}

	async getApply() {
		const res = await Business.findAll({
			where: {
				status: "待审核"
			}
		})
		return res
	}

	async passBusiness(id) {
		await Business.update({
			status: "营业中"
		}, {
			where: { id }
		})
	}

	async getAll() {
		return await Business.findAll({
			where: {
				status: '营业中'
			}
		})
	}

	async updateInfo({ business_name, director, phone }, id) {

		const whereOpt = {}
		business_name && Object.assign(whereOpt, { business_name })
		director && Object.assign(whereOpt, { director })
		phone && Object.assign(whereOpt, { phone })
		await Business.update(whereOpt, {
			where: {
				id
			}
		});
	}

	async updateStatus(id) {
		await Business.update({
			status: "空闲中"
		}, {
			where: { id }
		})
	}

	async getBusinessInfo({ phone, pwd }) {
		const res = await Business.findOne({
			where: {
				phone,
				password: pwd,
				status:"营业中"
			},
		})
		return res ? res.dataValues : null
	}
}

module.exports = new operationBusiness()